CRYPTO(9)	       FreeBSD Kernel Developer's Manual	     CRYPTO(9)

NNAAMMEE
     ccrryyppttoo -- API for cryptographic services in the kernel

SSYYNNOOPPSSIISS
     ##iinncclluuddee <<ooppeennccrryyppttoo//ccrryyppttooddeevv..hh>>

     _i_n_t_3_2___t
     ccrryyppttoo__ggeett__ddrriivveerriidd(_u___i_n_t_8___t);

     _i_n_t
     ccrryyppttoo__rreeggiisstteerr(_u___i_n_t_3_2___t, _i_n_t, _u___i_n_t_1_6___t, _u___i_n_t_3_2___t,
	 _i_n_t (_*)(_v_o_i_d _*_, _u___i_n_t_3_2___t _*_, _s_t_r_u_c_t _c_r_y_p_t_o_i_n_i _*),
	 _i_n_t (_*)(_v_o_i_d _*_, _u___i_n_t_6_4___t), _i_n_t (_*)(_v_o_i_d _*_, _s_t_r_u_c_t _c_r_y_p_t_o_p _*),
	 _v_o_i_d _*);

     _i_n_t
     ccrryyppttoo__kkrreeggiisstteerr(_u___i_n_t_3_2___t, _i_n_t, _u___i_n_t_3_2___t,
	 _i_n_t (_*)(_v_o_i_d _*_, _s_t_r_u_c_t _c_r_y_p_t_k_o_p _*), _v_o_i_d _*);

     _i_n_t
     ccrryyppttoo__uunnrreeggiisstteerr(_u___i_n_t_3_2___t, _i_n_t);

     _i_n_t
     ccrryyppttoo__uunnrreeggiisstteerr__aallll(_u___i_n_t_3_2___t);

     _v_o_i_d
     ccrryyppttoo__ddoonnee(_s_t_r_u_c_t _c_r_y_p_t_o_p _*);

     _v_o_i_d
     ccrryyppttoo__kkddoonnee(_s_t_r_u_c_t _c_r_y_p_t_k_o_p _*);

     _i_n_t
     ccrryyppttoo__nneewwsseessssiioonn(_u___i_n_t_6_4___t _*, _s_t_r_u_c_t _c_r_y_p_t_o_i_n_i _*, _i_n_t);

     _i_n_t
     ccrryyppttoo__ffrreeeesseessssiioonn(_u___i_n_t_6_4___t);

     _i_n_t
     ccrryyppttoo__ddiissppaattcchh(_s_t_r_u_c_t _c_r_y_p_t_o_p _*);

     _i_n_t
     ccrryyppttoo__kkddiissppaattcchh(_s_t_r_u_c_t _c_r_y_p_t_k_o_p _*);

     _i_n_t
     ccrryyppttoo__uunnbblloocckk(_u___i_n_t_3_2___t, _i_n_t);

     _s_t_r_u_c_t _c_r_y_p_t_o_p _*
     ccrryyppttoo__ggeettrreeqq(_i_n_t);

     _v_o_i_d
     ccrryyppttoo__ffrreeeerreeqq(_v_o_i_d);

     #define CRYPTO_SYMQ     0x1
     #define CRYPTO_ASYMQ    0x2

     #define EALG_MAX_BLOCK_LEN      16

     struct cryptoini {
	     int		cri_alg;
	     int		cri_klen;
	     int		cri_rnd;
	     caddr_t		cri_key;
	     u_int8_t		cri_iv[EALG_MAX_BLOCK_LEN];
	     struct cryptoini  *cri_next;
     };

     struct cryptodesc {
	     int		crd_skip;
	     int		crd_len;
	     int		crd_inject;
	     int		crd_flags;
	     struct cryptoini	CRD_INI;
	     struct cryptodesc *crd_next;
     };

     struct cryptop {
	     TAILQ_ENTRY(cryptop) crp_next;
	     u_int64_t		crp_sid;
	     int		crp_ilen;
	     int		crp_olen;
	     int		crp_etype;
	     int		crp_flags;
	     caddr_t		crp_buf;
	     caddr_t		crp_opaque;
	     struct cryptodesc *crp_desc;
	     int	      (*crp_callback) (struct cryptop *);
	     caddr_t		crp_mac;
     };

     struct crparam {
	     caddr_t	     crp_p;
	     u_int	     crp_nbits;
     };

     #define CRK_MAXPARAM    8

     struct cryptkop {
	     TAILQ_ENTRY(cryptkop) krp_next;
	     u_int		krp_op; 	/* ie. CRK_MOD_EXP or other */
	     u_int		krp_status;	/* return status */
	     u_short		krp_iparams;	/* # of input parameters */
	     u_short		krp_oparams;	/* # of output parameters */
	     u_int32_t		krp_hid;
	     struct crparam	krp_param[CRK_MAXPARAM];
	     int	       (*krp_callback)(struct cryptkop *);
     };

DDEESSCCRRIIPPTTIIOONN
     ccrryyppttoo is a framework for drivers of cryptographic hardware to register
     with the kernel so ``consumers'' (other kernel subsystems, and users
     through the _/_d_e_v_/_c_r_y_p_t_o device) are able to make use of it.  Drivers reg-
     ister with the framework the algorithms they support, and provide entry
     points (functions) the framework may call to establish, use, and tear
     down sessions.  Sessions are used to cache cryptographic information in a
     particular driver (or associated hardware), so initialization is not
     needed with every request.  Consumers of cryptographic services pass a
     set of descriptors that instruct the framework (and the drivers regis-
     tered with it) of the operations that should be applied on the data (more
     than one cryptographic operation can be requested).

     Keying operations are supported as well.  Unlike the symmetric operators
     described above, these sessionless commands perform mathematical opera-
     tions using input and output parameters.

     Since the consumers may not be associated with a process, drivers may not
     sleep(9).	The same holds for the framework.  Thus, a callback mechanism
     is used to notify a consumer that a request has been completed (the call-
     back is specified by the consumer on an per-request basis).  The callback
     is invoked by the framework whether the request was successfully com-
     pleted or not.  An error indication is provided in the latter case.  A
     specific error code, EAGAIN, is used to indicate that a session number
     has changed and that the request may be re-submitted immediately with the
     new session number.  Errors are only returned to the invoking function if
     not enough information to call the callback is available (meaning, there
     was a fatal error in verifying the arguments).  For session initializa-
     tion and teardown there is no callback mechanism used.

     The ccrryyppttoo__nneewwsseessssiioonn() routine is called by consumers of cryptographic
     services (such as the ipsec(4) stack) that wish to establish a new ses-
     sion with the framework.  On success, the first argument will contain the
     Session Identifier (SID).	The second argument contains all the necessary
     information for the driver to establish the session.  The third argument
     indicates whether a hardware driver (1) should be used or not (0).  The
     various fields in the _c_r_y_p_t_o_i_n_i structure are:

     _c_r_i___a_l_g   Contains an algorithm identifier.  Currently supported algo-
	       rithms are:

	       CRYPTO_DES_CBC
	       CRYPTO_3DES_CBC
	       CRYPTO_BLF_CBC
	       CRYPTO_CAST_CBC
	       CRYPTO_SKIPJACK_CBC
	       CRYPTO_MD5_HMAC
	       CRYPTO_SHA1_HMAC
	       CRYPTO_RIPEMD160_HMAC
	       CRYPTO_MD5_KPDK
	       CRYPTO_SHA1_KPDK
	       CRYPTO_AES_CBC
	       CRYPTO_ARC4
	       CRYPTO_MD5
	       CRYPTO_SHA1
	       CRYPTO_SHA2_HMAC
	       CRYPTO_NULL_HMAC
	       CRYPTO_NULL_CBC

     _c_r_i___k_l_e_n  Specifies the length of the key in bits, for variable-size key
	       algorithms.

     _c_r_i___r_n_d   Specifies the number of rounds to be used with the algorithm,
	       for variable-round algorithms.

     _c_r_i___k_e_y   Contains the key to be used with the algorithm.

     _c_r_i___i_v    Contains an explicit initialization vector (IV), if it does not
	       prefix the data.  This field is ignored during initialization.
	       If no IV is explicitly passed (see below on details), a random
	       IV is used by the device driver processing the request.

     _c_r_i___n_e_x_t  Contains a pointer to another _c_r_y_p_t_o_i_n_i structure.  Multiple
	       such structures may be linked to establish multi-algorithm ses-
	       sions (ipsec(4) is an example consumer of such a feature).

     The _c_r_y_p_t_o_i_n_i structure and its contents will not be modified by the
     framework (or the drivers used).  Subsequent requests for processing that
     use the SID returned will avoid the cost of re-initializing the hardware
     (in essence, SID acts as an index in the session cache of the driver).

     ccrryyppttoo__ffrreeeesseessssiioonn() is called with the SID returned by
     ccrryyppttoo__nneewwsseessssiioonn() to disestablish the session.

     ccrryyppttoo__ddiissppaattcchh() is called to process a request.	The various fields in
     the _c_r_y_p_t_o_p structure are:

     _c_r_p___s_i_d	   Contains the SID.

     _c_r_p___i_l_e_n	   Indicates the total length in bytes of the buffer to be
		   processed.

     _c_r_p___o_l_e_n	   On return, contains the total length of the result.	For
		   symmetric crypto operations, this will be the same as the
		   input length.  This will be used if the framework needs to
		   allocate a new buffer for the result (or for re-formatting
		   the input).

     _c_r_p___c_a_l_l_b_a_c_k  This routine is invoked upon completion of the request,
		   whether successful or not.  It is invoked through the
		   ccrryyppttoo__ddoonnee() routine.  If the request was not successful,
		   an error code is set in the _c_r_p___e_t_y_p_e field.  It is the
		   responsibility of the callback routine to set the appropri-
		   ate spl(9) level.

     _c_r_p___e_t_y_p_e	   Contains the error type, if any errors were encountered, or
		   zero if the request was successfully processed.  If the
		   EAGAIN error code is returned, the SID has changed (and has
		   been recorded in the _c_r_p___s_i_d field).  The consumer should
		   record the new SID and use it in all subsequent requests.
		   In this case, the request may be re-submitted immediately.
		   This mechanism is used by the framework to perform session
		   migration (move a session from one driver to another,
		   because of availability, performance, or other considera-
		   tions).

		   Note that this field only makes sense when examined by the
		   callback routine specified in _c_r_p___c_a_l_l_b_a_c_k.	Errors are
		   returned to the invoker of ccrryyppttoo__pprroocceessss() only when
		   enough information is not present to call the callback rou-
		   tine (i.e., if the pointer passed is NULL or if no callback
		   routine was specified).

     _c_r_p___f_l_a_g_s	   Is a bitmask of flags associated with this request.	Cur-
		   rently defined flags are:

		   CRYPTO_F_IMBUF  The buffer pointed to by _c_r_p___b_u_f is an mbuf
				   chain.

     _c_r_p___b_u_f	   Points to the input buffer.	On return (when the callback
		   is invoked), it contains the result of the request.	The
		   input buffer may be an mbuf chain or a contiguous buffer,
		   depending on _c_r_p___f_l_a_g_s.

     _c_r_p___o_p_a_q_u_e    This is passed through the crypto framework untouched and
		   is intended for the invoking application's use.

     _c_r_p___d_e_s_c	   This is a linked list of descriptors.  Each descriptor pro-
		   vides information about what type of cryptographic opera-
		   tion should be done on the input buffer.  The various
		   fields are:

		   _c_r_d___s_k_i_p    The offset in the input buffer where processing
			       should start.

		   _c_r_d___l_e_n     How many bytes, after _c_r_d___s_k_i_p, should be pro-
			       cessed.

		   _c_r_d___i_n_j_e_c_t  Offset from the beginning of the buffer to
			       insert any results.  For encryption algorithms,
			       this is where the initialization vector (IV)
			       will be inserted when encrypting or where it
			       can be found when decrypting (subject to
			       _c_r_d___f_l_a_g_s).  For MAC algorithms, this is where
			       the result of the keyed hash will be inserted.

		   _c_r_d___f_l_a_g_s   The following flags are defined:

			       CRD_F_ENCRYPT	  For encryption algorithms,
						  this bit is set when encryp-
						  tion is required (when not
						  set, decryption is per-
						  formed).

			       CRD_F_IV_PRESENT   For encryption algorithms,
						  this bit is set when the IV
						  already precedes the data,
						  so the _c_r_d___i_n_j_e_c_t value will
						  be ignored and no IV will be
						  written in the buffer.  Oth-
						  erwise, the IV used to
						  encrypt the packet will be
						  written at the location
						  pointed to by _c_r_d___i_n_j_e_c_t.
						  The IV length is assumed to
						  be equal to the blocksize of
						  the encryption algorithm.
						  Some applications that do
						  special ``IV cooking'', such
						  as the half-IV mode in
						  ipsec(4), can use this flag
						  to indicate that the IV
						  should not be written on the
						  packet.  This flag is typi-
						  cally used in conjunction
						  with the CRD_F_IV_EXPLICIT
						  flag.

			       CRD_F_IV_EXPLICIT  For encryption algorithms,
						  this bit is set when the IV
						  is explicitly provided by
						  the consumer in the _c_r_i___i_v
						  fields.  Otherwise, for
						  encryption operations the IV
						  is provided for by the
						  driver used to perform the
						  operation, whereas for
						  decryption operations it is
						  pointed to by the _c_r_d___i_n_j_e_c_t
						  field.  This flag is typi-
						  cally used when the IV is
						  calculated ``on the fly'' by
						  the consumer, and does not
						  precede the data (some
						  ipsec(4) configurations, and
						  the encrypted swap are two
						  such examples).

			       CRD_F_COMP	  For compression algorithms,
						  this bit is set when com-
						  pression is required (when
						  not set, decompression is
						  performed).

		   _C_R_D___I_N_I     This _c_r_y_p_t_o_i_n_i structure will not be modified
			       by the framework or the device drivers.	Since
			       this information accompanies every crypto-
			       graphic operation request, drivers may re-ini-
			       tialize state on-demand (typically an expensive
			       operation).  Furthermore, the cryptographic
			       framework may re-route requests as a result of
			       full queues or hardware failure, as described
			       above.

		   _c_r_d___n_e_x_t    Point to the next descriptor.  Linked opera-
			       tions are useful in protocols such as ipsec(4),
			       where multiple cryptographic transforms may be
			       applied on the same block of data.

     ccrryyppttoo__ggeettrreeqq() allocates a _c_r_y_p_t_o_p structure with a linked list of as
     many _c_r_y_p_t_o_d_e_s_c structures as were specified in the argument passed to
     it.

     ccrryyppttoo__ffrreeeerreeqq() deallocates a structure _c_r_y_p_t_o_p and any _c_r_y_p_t_o_d_e_s_c
     structures linked to it.  Note that it is the responsibility of the call-
     back routine to do the necessary cleanups associated with the opaque
     field in the _c_r_y_p_t_o_p structure.

     ccrryyppttoo__kkddiissppaattcchh() is called to perform a keying operation.  The various
     fields in the _c_r_y_p_t_k_o_p structure are:

     _k_r_p___o_p	    Operation code, such as CRK_MOD_EXP.

     _k_r_p___s_t_a_t_u_s     Return code.  This _e_r_r_n_o-style variable indicates whether
		    lower level reasons for operation failure.

     _k_r_p___i_p_a_r_a_m_s    Number if input parameters to the specified operation.
		    Note that each operation has a (typically hardwired) num-
		    ber of such parameters.

     _k_r_p___o_p_a_r_a_m_s    Number if output parameters from the specified operation.
		    Note that each operation has a (typically hardwired) num-
		    ber of such parameters.

     _k_r_p___k_v_p	    An array of kernel memory blocks containing the parame-
		    ters.

     _k_r_p___h_i_d	    Identifier specifying which low-level driver is being
		    used.

     _k_r_p___c_a_l_l_b_a_c_k   Callback called on completion of a keying operation.

DDRRIIVVEERR--SSIIDDEE AAPPII
     The ccrryyppttoo__ggeett__ddrriivveerriidd(), ccrryyppttoo__rreeggiisstteerr(), ccrryyppttoo__kkrreeggiisstteerr(),
     ccrryyppttoo__uunnrreeggiisstteerr(), ccrryyppttoo__uunnbblloocckk(), and ccrryyppttoo__ddoonnee() routines are
     used by drivers that provide support for cryptographic primitives to reg-
     ister and unregister with the kernel crypto services framework.  Drivers
     must first use the ccrryyppttoo__ggeett__ddrriivveerriidd() function to acquire a driver
     identifier, specifying the _c_c___f_l_a_g_s as an argument (normally 0, but soft-
     ware-only drivers should specify CRYPTOCAP_F_SOFTWARE).  For each algo-
     rithm the driver supports, it must then call ccrryyppttoo__rreeggiisstteerr().  The
     first two arguments are the driver and algorithm identifiers.  The next
     two arguments specify the largest possible operator length (in bits,
     important for public key operations) and flags for this algorithm.  The
     last four arguments must be provided in the first call to
     ccrryyppttoo__rreeggiisstteerr() and are ignored in all subsequent calls.  They are
     pointers to three driver-provided functions that the framework may call
     to establish new cryptographic context with the driver, free already
     established context, and ask for a request to be processed (encrypt,
     decrypt, etc.); and an opaque parameter to pass when calling each of
     these routines.  ccrryyppttoo__uunnrreeggiisstteerr() is called by drivers that wish to
     withdraw support for an algorithm.  The two arguments are the driver and
     algorithm identifiers, respectively.  Typically, drivers for PCMCIA
     crypto cards that are being ejected will invoke this routine for all
     algorithms supported by the card.	ccrryyppttoo__uunnrreeggiisstteerr__aallll() will unregis-
     ter all algorithms registered by a driver and the driver will be disabled
     (no new sessions will be allocated on that driver, and any existing ses-
     sions will be migrated to other drivers).	The same will be done if all
     algorithms associated with a driver are unregistered one by one.

     The calling convention for the three driver-supplied routines is:

     _i_n_t (**nneewwsseessssiioonn)(_v_o_i_d _*, _u___i_n_t_3_2___t _*, _s_t_r_u_c_t _c_r_y_p_t_o_i_n_i _*);
     _i_n_t (**ffrreeeesseessssiioonn)(_v_o_i_d _*, _u___i_n_t_6_4___t);
     _i_n_t (**pprroocceessss)(_v_o_i_d _*, _s_t_r_u_c_t _c_r_y_p_t_o_p _*);
     _i_n_t (**kkpprroocceessss)(_v_o_i_d _*, _s_t_r_u_c_t _c_r_y_p_t_k_o_p _*);

     On invocation, the first argument to all routines is an opaque data value
     supplied when the algorithm is registered with ccrryyppttoo__rreeggiisstteerr().	The
     second argument to nneewwsseessssiioonn() contains the driver identifier obtained
     via ccrryyppttoo__ggeett__ddrriivveerriidd().  On successful return, it should contain a
     driver-specific session identifier.  The third argument is identical to
     that of ccrryyppttoo__nneewwsseessssiioonn().

     The ffrreeeesseessssiioonn() routine takes as arguments the opaque data value and
     the SID (which is the concatenation of the driver identifier and the
     driver-specific session identifier).  It should clear any context associ-
     ated with the session (clear hardware registers, memory, etc.).

     The pprroocceessss() routine is invoked with a request to perform crypto pro-
     cessing.  This routine must not block, but should queue the request and
     return immediately.  Upon processing the request, the callback routine
     should be invoked.  In case of an unrecoverable error, the error indica-
     tion must be placed in the _c_r_p___e_t_y_p_e field of the _c_r_y_p_t_o_p structure.
     When the request is completed, or an error is detected, the pprroocceessss()
     routine should invoke ccrryyppttoo__ddoonnee().  Session migration may be performed,
     as mentioned previously.

     In case of a temporary resource exhaustion, the pprroocceessss() routine may
     return ERESTART in which case the crypto services will requeue the
     request, mark the driver as ``blocked'', and stop submitting requests for
     processing.  The driver is then responsible for notifying the crypto ser-
     vices when it is again able to process requests through the
     ccrryyppttoo__uunnbblloocckk() routine.	This simple flow control mechanism should only
     be used for short-lived resource exhaustion as it causes operations to be
     queued in the crypto layer.  Doing so is preferable to returning an error
     in such cases as it can cause network protocols to degrade performance by
     treating the failure much like a lost packet.

     The kkpprroocceessss() routine is invoked with a request to perform crypto key
     processing.  This routine must not block, but should queue the request
     and return immediately.  Upon processing the request, the callback rou-
     tine should be invoked.  In case of an unrecoverable error, the error
     indication must be placed in the _k_r_p___s_t_a_t_u_s field of the _c_r_y_p_t_k_o_p struc-
     ture.  When the request is completed, or an error is detected, the
     kkpprroocceessss() routine should invoked ccrryyppttoo__kkddoonnee().

RREETTUURRNN VVAALLUUEESS
     ccrryyppttoo__rreeggiisstteerr(), ccrryyppttoo__kkrreeggiisstteerr(), ccrryyppttoo__uunnrreeggiisstteerr(),
     ccrryyppttoo__nneewwsseessssiioonn(), ccrryyppttoo__ffrreeeesseessssiioonn(), and ccrryyppttoo__uunnbblloocckk() return 0
     on success, or an error code on failure.  ccrryyppttoo__ggeett__ddrriivveerriidd() returns a
     non-negative value on error, and -1 on failure.  ccrryyppttoo__ggeettrreeqq() returns
     a pointer to a _c_r_y_p_t_o_p structure and NULL on failure.  ccrryyppttoo__ddiissppaattcchh()
     returns EINVAL if its argument or the callback function was NULL, and 0
     otherwise.  The callback is provided with an error code in case of fail-
     ure, in the _c_r_p___e_t_y_p_e field.

FFIILLEESS
     sys/opencrypto/crypto.c  most of the framework code

SSEEEE AALLSSOO
     ipsec(4), malloc(9), sleep(9)

HHIISSTTOORRYY
     The cryptographic framework first appeared in OpenBSD 2.7 and was written
     by Angelos D. Keromytis <angelos@openbsd.org>.

BBUUGGSS
     The framework currently assumes that all the algorithms in a
     ccrryyppttoo__nneewwsseessssiioonn() operation must be available by the same driver.  If
     that is not the case, session initialization will fail.

     The framework also needs a mechanism for determining which driver is best
     for a specific set of algorithms associated with a session.  Some type of
     benchmarking is in order here.

     Multiple instances of the same algorithm in the same session are not sup-
     ported.  Note that 3DES is considered one algorithm (and not three
     instances of DES).  Thus, 3DES and DES could be mixed in the same
     request.

FreeBSD 6.0		       October 14, 2002 		   FreeBSD 6.0
